package game.module.nn.processor;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.nn.bean.NnRound;
import game.module.nn.logic.NnDataManager;
import game.module.nn.logic.NnDissmissRoomManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageNn.C2SVoteDissNnroom;
import lua.LuaMessageNn.PushVoteDissNnroom;
import lua.LuaMessageNn.S2CVoteDissNnroom;

@MsgCodeAnn(msgcode = C2SVoteDissNnroom.id, accessLimit = 500)
public class NnFoceDismissRoom extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(NnFoceDismissRoom.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw requestMessage) throws Exception {
		int playerId = playingRole.getId();
		logger.info("nn force to dismiss room,playerId={}", playerId);
		// 房间是否存在
		// 房间是否存在
		C2SVoteDissNnroom reqMsg = C2SVoteDissNnroom.parse(requestMessage);
		byte vote = reqMsg.vote;
		NnRound nnround = NnDataManager.getInstance().getNnRoom(playerId);
		if (nnround == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		List<Integer> players = nnround.getPlayerIds();
		boolean votediss[]  = nnround.getVotediss();
		int currents = players.indexOf(playerId);
		
		
		S2CVoteDissNnroom msg = new S2CVoteDissNnroom();
		playingRole.writeAndFlush(msg.build(playingRole.alloc()));
		
		PushVoteDissNnroom pushmsg = new  PushVoteDissNnroom();
		pushmsg.index = (byte)currents;
		pushmsg.result = vote;
		if(vote == 0) {
			NnDissmissRoomManager.getInstance().cancleDissmiss(nnround.getRoomUuid());
			nnround.setStartVoteTime(0);
			nnround.setVoteplayerIndex((byte)0);
			Arrays.fill(votediss, false);
		}else {
			NnDissmissRoomManager.getInstance().createRemoveNnRound(playerId);
			votediss[currents] = true;
		}
		for(Integer aplayer:players) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aplayer);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushmsg.build(pr.alloc()));
				// 推送关于出牌的信息
			}
		}
		for(boolean flag:votediss) {
			if(!flag)
				return;
		}
		NnDissmissRoomManager.getInstance().advanceCancle(playerId);
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {

	}

}
